package com.github.gaojh.starter.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;

/**
 * @author gaojh
 * @since 2020/4/14
 */
public class RabbitProducer {

    private RabbitContext rabbitContext;

    public RabbitProducer(RabbitContext rabbitContext) {
        this.rabbitContext = rabbitContext;
    }

    public void sendQueue(Queue queue, Object message) throws Exception {
        Channel channel = rabbitContext.getChannel("");
        if (message instanceof String) {
            channel.basicPublish("", queue.getQueue(), null, message.toString().getBytes());
        } else {
            channel.basicPublish("", queue.getQueue(), null, JSONUtil.toJsonPrettyStr(message).getBytes());
        }
    }

    public void sendExchange(Exchange exchange, Object message) throws Exception {
        Channel channel = rabbitContext.getChannel(exchange.getExchange());
        if (message instanceof String) {
            channel.basicPublish(exchange.getExchange(), "", null, message.toString().getBytes());
        } else {
            channel.basicPublish(exchange.getExchange(), "", null, JSONUtil.toJsonPrettyStr(message).getBytes());
        }
    }
}
